﻿package engine.game.world {
	import engine.base.GameBase;
	import engine.game.world.Tile;
	import engine.core.Array2;
	import flash.display.BitmapData;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	import engine.game.Camera;
	import engine.managers.AssetManager;
	
	/**
	* A map layer object used as part of the map object for 
	* representing maps within the world.
	* @author Jon Smelquist
	*/
	public class MapLayer extends GameBase {
		private var _tileArray:Array2;
		private var _asset:String;
		
		public function setTile(x:int, y:int, tile:Tile):void { _tileArray.set(x, y, tile); }
		public function getTile(x:int, y:int):Tile { return _tileArray.get(x, y); }
		
		public function MapLayer(width:int,height:int,asset:String) {
			super(100);
			_display = new BitmapData( width, height, true, 0x00000000 );
			_tileArray = new Array2(width, height);
			_asset = asset;
		}
		
		/**
		 * Update all Tiles that are in view of the camera, this is
		 * so that we dont waste processing on Tiles that are outside 
		 * the viewers scope.
		 */
		protected override function update():void {
			// val >> 5 is an extremely fast way to divide by 32
			// val & 31 is an extremely fast way to modulus by 32
			//var camRect:Rectangle = Camera.getInstance().rect;
			//var xStart:int = int(camRect.x >> 5);
			//var yStart:int = int(camRect.y >> 5);
			//var tile:Tile;
			//for (var y:int = 0; y < (camRect.height >> 5); y++) {
			//	for (var x:int = 0; x < (camRect.width >> 5); x++) {
			//		tile = _tileArray.get(yStart + y, xStart + x);
			//		tile.processTick(_msTick);
			//	}
			//}
		}
		
		/**
		 * Draw all the Tiles that are within the cameras view to the passed
		 * surface object.
		 * @param	surface		Surface to draw onto.
		 * @param	camRect		Rectangle of our cameras view.
		 */
		public override function draw(surface:BitmapData, camRect:Rectangle):void {
			// val >> 5 is an extremely fast way to divide by 32
			// val & 31 is an extremely fast way to modulus by 32
			var source:BitmapData = AssetManager.getInstance().getAsset(_asset);
			
			var tile:Tile;
			var xStart:int = int(camRect.x >> 5);
			var yStart:int = int(camRect.y >> 5);
			for (var y:int = 0; y < (camRect.height >> 5); y++) {
				for (var x:int = 0; x < (camRect.width >> 5); x++) {
					tile = _tileArray.get(yStart+y, xStart+x);
					var length:int = tile.imageLayers.length;
					for (var i:int = 0; i < length; i++)
					{
						var sourceRect:Rectangle = new Rectangle( (tile.imageLayers[i] % 10) * 32, int(tile.imageLayers[i] / 10) * 32, 32, 32 );
						surface.copyPixels(source, sourceRect, new Point(tile.position.x - camRect.x, tile.position.y - camRect.y));
					}
				}
			}
		}
		
	}
	
}